package com.hbhmzy.contact;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Looper;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hbhmzy.call.R;
import com.hbhmzy.utils.NovUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

public class ContactsActivity extends Activity
        implements ActivityCompat.OnRequestPermissionsResultCallback{

    private static final String TAG = "ContactsActivity";
    private static final int REQUEST_READ_CONTACTS_PERMISSION = 3;
    /**
     * 判断当前页面是否结束(防止encode未完成页面就退出或者重新加载了，会造成闪退)
     */
//    public static boolean isFinish = true;
    private ImageView ivBack;	//返回按钮
    private Button addContact;	//添加联系人
    private EditText etSearch;	//搜索框
    private ImageView ivClearText; //当搜索框内有内容的时候显示
    private SideBar sideBar;	//索引
    private ListView mListView;
    private List<SortModel> mAllContactsList;
    private ContactsSortAdapter adapter;
    // 汉字转换成拼音的类
    private static CharacterParser characterParser;
    // 根据拼音来排列 ListView 里面的数据类
    private PinyinComparator pinyinComparator;
    // 用来创建存储通讯录信息的数据库
    private ContactDBHelper dbHelper;
    // 数据库的名字
    public static final String dbName = "mycontact.db3";
    // 本地联系人数据库文件的绝对路径
    String dbPath = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_contacts);
//        isFinish=false;
        //设置状态栏颜色
//        Sofia.with(this).statusBarBackground(getResources().getColor(R.color.GREEN_ROOT));

        //启动时解密数据库
        dbPath = getApplicationContext().getDatabasePath(ContactsActivity.dbName).getAbsolutePath();
        Base64Util.decode(dbPath);

        //检查权限
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS_PERMISSION);
        }else {
            initView();
            initListener();
            loadContacts();
        }
    }

    //加密本地的联系人数据库 mycontact.db3,关闭ContactDBHelper里的SQLiteDatabase >>>>
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy");
        Base64Util.encode(dbPath);
        if (dbHelper != null) {
            dbHelper.close();
        }
//        isFinish=true;
    }

    private void initView() {
        //初始化标题栏
        ivBack = findViewById(R.id.root_back2);
        TextView title = findViewById(R.id.root_title2);
        title.setText("通讯录");
        addContact = findViewById(R.id.root_select2);
        addContact.setText("添加");

        sideBar = findViewById(R.id.sidebar);
        TextView dialog = findViewById(R.id.dialog);
        sideBar.setTextView(dialog);
        ivClearText = findViewById(R.id.ivClearText);
        etSearch = findViewById(R.id.et_search);
        mListView = findViewById(R.id.lv_contacts);

        characterParser = CharacterParser.getInstance();
        mAllContactsList = new ArrayList<>();
        pinyinComparator = new PinyinComparator();
        Collections.sort(mAllContactsList, pinyinComparator);// 根据a~z进行排序源数据
        adapter = new ContactsSortAdapter(this, mAllContactsList);
        mListView.setAdapter(adapter);
    }

    private void initListener() {
        // 返回
        ivBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 清除输入字符
        ivClearText.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearch.setText("");
            }
        });

        // 添加联系人
        addContact.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent addIntent = new Intent(ContactsActivity.this, ContactAddActivity.class);
                startActivityForResult(addIntent,Constant.ADD_CONTACT);
            }
        });

        // 当搜索框输入的字符变化时
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable e) {
                String content = etSearch.getText().toString();
                if ("".equals(content)) {  // 搜索框为空时隐藏清除图标
                    ivClearText.setVisibility(View.INVISIBLE);
                } else {
                    ivClearText.setVisibility(View.VISIBLE);
                }
                if (content.length() > 0) {
                    ArrayList<SortModel> fileterList = (ArrayList<SortModel>) search(content);
                    adapter.updateListView(fileterList);
                } else {
                    adapter.updateListView(mAllContactsList);
                }
                mListView.setSelection(0);
            }
        });

        // 设置右侧[A-Z]快速导航栏触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    mListView.setSelection(position);
                }
            }
        });

        // listView 中每一项的点击事件： 跳转到联系人的具体信息界面
        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long arg3) {
                SortModel sortModel = (SortModel) adapterView.getItemAtPosition(position);
                String name = sortModel.name; // 该 item 中 的姓名
                String number = sortModel.number; // 该 item 中 的号码

                Intent intent = new Intent(ContactsActivity.this, ContactDetailActivity.class);
                intent.putExtra("name",name);
                intent.putExtra("number",number);
                startActivityForResult(intent,Constant.CONTACT_DETAIL);
            }
        });

    }

    /** 加载联系人 */
    private void loadContacts(){
        // 打开数据库，创建表 contact_info
        dbHelper = new ContactDBHelper(this, dbName, null, 1);
        // 第一次启动通讯录时加载联系人, 并将联系人信息插入本地数据库
        if (NovUtil.isContactsFirstStart(this)) {
            Log.e(TAG, "loadContactsFirst");
            loadContactsFirst();
        } else {
            Log.e(TAG, "loadContactsAfter");
            loadContactsAfter();
        }
    }

    /**第一次运行程序时从手机读取数据库的联系人信息，并将信息插入本地自建的数据库中*/
    private void loadContactsFirst() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ContentResolver resolver = getApplicationContext().getContentResolver();
                    // 按照顺序获取手机通讯录中的姓名和号码
                    Cursor cursor = resolver.query(Phone.CONTENT_URI,
                            new String[] {
                                    Phone.DISPLAY_NAME,
                                    Phone.NUMBER,
                                    "sort_key" },
                            null, null,"sort_key COLLATE LOCALIZED ASC");

                    mAllContactsList = new ArrayList<>();
                    if (cursor == null || cursor.getCount() == 0) {
                        Toast.makeText(getApplicationContext(), "未获得读取联系人权限 或 未获得联系人数据", Toast.LENGTH_SHORT).show();
                    }else if (cursor.getCount() > 0) {
                        // 遍历通讯录中的联系人信息
                        while (cursor.moveToNext()) {
                            String contactName = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
                            Log.e("contactName", contactName);
                            Log.e("phoneNumber", cursor.getString(cursor.getColumnIndex(Phone.NUMBER)));
                            String phoneNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
                            if (TextUtils.isEmpty(phoneNumber)){
//								continue;
                                phoneNumber="0";
                            }

                            // 将 contactName 转化为 sortKey (解决某些 Android 版本中的 sortKey 是 contactName 的问题)
//							String sortKey = cursor.getString(cursor.getColumnIndex("sort_key"));
                            String sortKey = ContactsActivity.getSortKey(contactName);
                            SortModel sortModel = new SortModel(contactName, phoneNumber, sortKey);
                            // 优先使用系统 sortkey 取,取不到再使用工具取
                            String sortLetters = getSortLetterBySortKey(sortKey);
                            if (sortLetters == null) {
                                sortLetters = getSortLetterByName(contactName);
                            }
                            sortModel.sortLetters = sortLetters;
                            sortModel.sortToken = parseSortKey(sortKey);
                            mAllContactsList.add(sortModel);
                            ContactDBManager.insert(dbHelper.getWritableDatabase(), contactName, phoneNumber, sortKey, null,
                                    null);
                        }
                    }
                    if (cursor != null) {
                        cursor.close();
                    }
                    // 遍历完通讯录信息后更新 UI
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Collections.sort(mAllContactsList, pinyinComparator);
                            adapter.updateListView(mAllContactsList);
                        }
                    });
                } catch (Exception e) {
                    Log.e("xbc", e.getLocalizedMessage());
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), "未获得读取联系人权限或未获得联系人数据", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            }
        }).start();
    }

    /**若运行程序不是第一次运行，则从本地自建的数据库中读取联系人信息*/
    private void loadContactsAfter() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mAllContactsList = new ArrayList<>();
                    // 按照顺序获取手机通讯录中的姓名和号码
                    Cursor cursor = dbHelper.getWritableDatabase().rawQuery("select * from contact_info order by sortKey COLLATE LOCALIZED ASC", null);
                    if (cursor == null || cursor.getCount() == 0) {
                        Toast.makeText(getApplicationContext(), "未获得读取联系人权限 或 未获得联系人数据", Toast.LENGTH_SHORT).show();
                    }
                    // contact_info:_id name number sortkey email address
                    else if (cursor.getCount() > 0) {
                        // 遍历通讯录中的联系人信息
                        while (cursor.moveToNext()) {
                            String contactName = cursor.getString(1);
                            String phoneNumber = cursor.getString(2);
                            if (TextUtils.isEmpty(phoneNumber)){
//								continue;
                                phoneNumber="";
                            }
                            String sortKey = cursor.getString(3);
                            SortModel sortModel = new SortModel(contactName, phoneNumber, sortKey);
                            // 优先使用系统 sortkey 取,取不到再使用工具取
                            String sortLetters = getSortLetterBySortKey(sortKey);
                            if (sortLetters == null) {
                                sortLetters = getSortLetterByName(contactName);
                            }
                            sortModel.sortLetters = sortLetters;
                            sortModel.sortToken = parseSortKey(sortKey);
                            mAllContactsList.add(sortModel);
                        }
                    }
                    if (cursor != null) {
                        cursor.close();
                    }
                    // 遍历完通讯录信息后更新 UI
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Collections.sort(mAllContactsList, pinyinComparator);
                            adapter.updateListView(mAllContactsList);
                        }
                    });
                } catch (Exception e) {
                    Log.e("xbc", e.getLocalizedMessage());
                }
            }
        }).start();
    }

    /**
     * 名字转拼音,取首字母
     */
    private String getSortLetterByName(String name) {
        String letter = "#";
        if (name == null) {
            return letter;
        }
        // 汉字转换成拼音
        String pinyin = characterParser.getSelling(name);
        String sortString = pinyin.substring(0, 1).toUpperCase(Locale.CHINESE);
        // 正则表达式，判断首字母是否是英文字母
        if (sortString.matches("[A-Z]")) {
            letter = sortString.toUpperCase(Locale.CHINESE);
        }
        return letter;
    }

    /**
     * 取sort_key的首字母
     */
    private String getSortLetterBySortKey(String sortKey) {
        if (sortKey == null || "".equals(sortKey.trim())) {
            return null;
        }
        String letter = "#";
        // 汉字转换成拼音
        String sortString = sortKey.trim().substring(0, 1).toUpperCase(Locale.CHINESE);
        // 正则表达式，判断首字母是否是英文字母
        if (sortString.matches("[A-Z]")) {
            letter = sortString.toUpperCase(Locale.CHINESE);
        }
        return letter;
    }

    /**
     * 名字转 sortKey eg: 丁聪 ---> DING 丁 CONG 聪
     */
    public static String getSortKey(String name) {
        String fltName = name.replace(" ", "");
        String sortKey = "#";
//		String reg = "[a-zA-Z]";

        //判断首字母是不是字母或汉字，如果不是则返回 #
        String a = String.valueOf(fltName.charAt(0));
        if (!characterParser.getSelling(a).matches("^[A-Za-z]+$")) {
            return sortKey;
        }

        StringBuilder buffer = new StringBuilder();
        String pinyin;
        for (int i = 0; i < fltName.length(); i++) {
            String c = String.valueOf(fltName.charAt(i));
            // 汉字转化为拼音
            pinyin = characterParser.getSelling(c);
            // 正则表达式，匹配由26个英文字母组成的字符串
            if (pinyin.matches("^[A-Za-z]+$")) {
                String temp = pinyin.toUpperCase(Locale.CHINESE);
                buffer.append(temp).append(" ").append(fltName.charAt(i)).append(" ");
            }
        }
        String str = buffer.toString();
        // 去掉尾部的空格
        sortKey = str.substring(0, str.length()-1);
        return sortKey;
    }

    /**
     * 解析sort_key,封装简拼,全拼
     *
     * @return SortToken
     */
    public SortToken parseSortKey(String sortKey) {
        SortToken token = new SortToken();
        String chReg = "[\\u4E00-\\u9FA5]+";// 中文字符串匹配
        // String chReg="[^\\u4E00-\\u9FA5]";//除中文外的字符匹配

        if (sortKey != null && sortKey.length() > 0) {
            // 其中包含的中文字符
            String[] enStrs = sortKey.replace(" ", "").split(chReg);
            for (String enStr : enStrs) {
                if (enStr.length() > 0) {
                    // 拼接简拼
                    token.simpleSpell += enStr.charAt(0);
                    token.wholeSpell += enStr;
                }
            }
        }
        // Log.e("sortKey: ", sortKey);
        // Log.e("simpleSpell: ", token.simpleSpell);
        // Log.e("wholeSpell: " , token.wholeSpell );
        return token;
    }

    /**
     * 模糊查询
     */
    private List<SortModel> search(String str) {
        List<SortModel> filterList = new ArrayList<>(); // 过滤后的list
        if (str.matches("^([0-9]|[/+]).*")) { // 正则表达式：匹配以数字或者加号开头的字符串(包括了带空格及-分割的号码)
            String simpleStr = str.replaceAll("\\-|\\s", "");  // 去掉横杠或空白符
            for (SortModel contact : mAllContactsList) {
                if (contact.number != null && contact.name != null) {
                    if (contact.simpleNumber.contains(simpleStr) || contact.name.contains(str)) {
                        if (!filterList.contains(contact)) {
                            filterList.add(contact);
                        }
                    }
                }
            }
        } else {
            for (SortModel contact : mAllContactsList) {
                if (contact.number != null && contact.name != null) {
                    // 姓名全匹配,姓名首字母简拼匹配,姓名全字母匹配
                    if (contact.name.toLowerCase(Locale.CHINESE).contains(str.toLowerCase(Locale.CHINESE))
                            || contact.sortKey.toLowerCase(Locale.CHINESE).replace(" ", "")
                            .contains(str.toLowerCase(Locale.CHINESE))
                            || contact.sortToken.simpleSpell.toLowerCase(Locale.CHINESE)
                            .contains(str.toLowerCase(Locale.CHINESE))
                            || contact.sortToken.wholeSpell.toLowerCase(Locale.CHINESE)
                            .contains(str.toLowerCase(Locale.CHINESE))) {
                        if (!filterList.contains(contact)) {
                            filterList.add(contact);
                        }
                    }
                }
            }
        }
        return filterList;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction()==KeyEvent.ACTION_DOWN){
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initView();
                initListener();
                loadContacts();
            }else {
                Toast.makeText(this, "未获取通讯录权限，请在权限设置中进行设置", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case Constant.ADD_CONTACT:
                if(resultCode == Activity.RESULT_OK){
                    loadContactsAfter();
                }
                break;

            case Constant.CONTACT_DETAIL:
                if(resultCode == Constant.DELETE_RESULT_CODE){
                    loadContactsAfter();
                }else if(resultCode == Constant.EDIT_RESULT_CODE){
                    loadContactsAfter();
                }
                break;
        }
    }
}